/**
 * ...
 * @author Cref
 */

package js.db;

import js.db.Connection;
import js.db.ResultSet;
import activex.adodb.RecordSet;

class ADOConnection implements Connection {

	private var cn:activex.adodb.Connection;
	public var ms(default,null):Bool;
	
	public static function open(constr:String):ADOConnection {
		var c = new activex.adodb.Connection();
		#if debug
		try{
			c.open(constr);
		}
		catch (e:Dynamic) {
			//trace(constr);
			throw e;
		}
		#else
		c.open(constr);
		#end
		return new ADOConnection(c);
	}
	
	public function new(cn:activex.adodb.Connection) {
		this.cn = cn;
		ms = cn.connectionString.indexOf('SQLNCLI') > 0 || cn.connectionString.indexOf('Microsoft') > 0;
	}

	public function request( s : String ) : ResultSet {
		//try {
			var n:Int = 0;
			var rs = new RecordSet();
			rs.cursorLocation = 3;
			// http://www.devguru.com/technologies/ado/quickref/recordset_open.html
			#if debug
			try{
			#end
			//	trace(s);
			rs.open(s, cn, 0, 1, 1);
			#if debug
			}
			catch (e:Dynamic) {
				trace(s);
				throw e;
			}
			#end
			return new ADOResultSet(rs);
			trace('>>>'+ n);
		//} catch( e : Dynamic ) {
		//	throw "Error while executing "+s+" ("+e+")";
		//}
	}

	//does not belong on connection instance!
	public function escape( s : String ) {
		return s.split("'").join("''");
	}

	//does not belong on connection instance!
	public function quote( s : String ) {
		//TODO: Base encode
		//if( s.indexOf("\000") >= 0 )
		//	return "x'"+new String(untyped _encode(s.__s,"0123456789ABCDEF".__s))+"'";
		return "'"+escape(s)+"'";
	}
	
	public function close() : Void if (cn.state>0) cn.close()
	
	//adds an SQL value to a StringBuf
	public function addValue( s : StringBuf, v : Dynamic ) {
		//if( untyped __call__("is_int", v) || __call__("is_null", v))
		if(v==null || Std.is(v,Int)) s.add(v);
		else if(Std.is(v,Bool)) s.add(v?'true':'false');
		else s.add(quote(Std.string(v)));
	}
	
	//TODO
	//not sure if this is available on all ADODB's
	public function lastInsertId() : Int {
		return -1;
	}
	
	//TODO
	//not sure yet what this function should return
	public function dbName() : String {
		return '';
	}
	
	public function startTransaction() : Void {
		//cn.
	}
	
	public function commit() : Void {
		
	}
	
	public function rollback() : Void {
		
	}
	
}